<?php

namespace App\Http\Middleware;

use Closure;
use Session, DB;

class CommonMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 获取路由信息
        $route = '/' . $request->path();
        $route = preg_replace('/\/\d+/', '',  $route); // 去除路由中的数字id
        // 验证登录状态 如果没有登录 跳转到登录页
        if(!Session::has('adminuserData') && $route !== '/admin/login'){
            return redirect('/admin/login');
        }
        // 查找一下所有启用的权限列表 判断当前的操作是否需要权限验证
        $rules = DB::table("rule")->where("status", 1)->lists('title', 'name');
        if (array_key_exists($route, $rules)){
            //获取当前用户的分组
            $groupid = DB::table("admin_user")
                    ->leftJoin("user_group", "admin_user.id", "=", "user_group.uid")
                    ->where("admin_user.id", Session::get("adminuserData")->id)
                    ->pluck("user_group.groupid");
            //由分组查询权限集合
            $lists = DB::table("group_rule")->where("id", $groupid)->pluck("rules"); //[1,2,3,4]
            //当前操作的权限ID
            $rule = DB::table("rule")->where("name", $route)->pluck("id"); //7
            if (!in_array($rule, explode(",", $lists))) {
                if($request->ajax()){
                    return response()->json(['status'=>0, 'info'=>'没有权限']);
                }
                return redirect("/tips")->with(["info" => "你无权".$rules[$route], "url" => $_SERVER["HTTP_REFERER"]]);
            }
        }
        return $next($request);
    }
}
